<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" queryCode="roleList"/>
    <TableHeader :can-collapsed="false">
      <template v-slot:right>
        <el-button
          type="primary"
          size="mini"
          :icon="CirclePlus"
          @click="onAddItem"
          >新增
        </el-button>
        <el-button
          type="danger"
          size="mini"
          :icon="Delete"
          @click="onDeleteItem(selectRows)"
          >删除
        </el-button>
      </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
            <!-- <el-tooltip effect="dark" content="刷新页面" placement="top">
              <el-button
                circle
                type="success"
                :icon="RefreshIcon"
                size="mini"
                @click="doRefresh"
              />
            </el-tooltip> -->
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    />
   
  <Dialog ref="dialog"  title="编辑信息" :form-items="formItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="formItems"
        ></BaseForm>
      </template>
  </Dialog>

      <Dialog
      ref="menuDialogRef"
      title="菜单权限"
    >
      <template #content>
        <el-tree
          ref="tree"
          :data="menuData"
          show-checkbox
          highlight-current 
          node-key="menuOid"
          :default-expanded-keys="defaultExpandedKeys"
          :default-checked-keys="defaultCheckedKeys"
          :props="defaultProps"
          @check-change="handleCheckChange"
        />
      </template>
    </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import { ElMessage } from 'element-plus';
import {onMounted, reactive, ref,shallowReactive } from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryRoleList,saveRole,updateRole,deleteBatchRole,getMenuListByRoleId,saveUserRight } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import { allMenuToTree } from '@/utils/index';
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { each } from 'lodash';
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const menuData = shallowReactive<Array<any>>([]);
const defaultProps = {
  children: "children",
  label: "menuName",
  checked: true,
  nodekey: "menuOid",
};
const roleModel = reactive({
  id: 0,
  roleOid:0,
  name: "",
  roleCode: "",
});
const defaultCheckedKeys = shallowReactive<Array<any>>([]);
const defaultExpandedKeys = shallowReactive<Array<any>>([]);
const selectedKeys = shallowReactive<Array<any>>([]);
let currentRoleOid: number;
const tableColumns = reactive([
  { label: "角色编码", 
    prop: "roleCode", 
    checked:true,
  },
  { label: "角色名", 
    prop: "name", 
    checked:true,
  },
  { label: "备注", 
    prop: "remark", 
    checked:true,
  },
  // { label: "状态", 
  //   prop: "state", 
  //   checked:true,
  // },

]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    handler: (row: any) => handleEdit(row),
  },
  {
    text: "权限分配",
    key: "edit",
    type: "primary",
    handler: (row: any) => showMenu(row),
  },
]);

const formItems = reactive([
  { label: "角色OID", 
    type: 'input',
    name: "roleOid", 
    value: 0,
    hidden: true,
    placeholder: '请输入角色OID',
    reset() {
                this.value = 0;
            },
  },
  { label: "角色编码", 
    type: 'input',
    name: "roleCode", 
    value: '',
    maxlength: 20,
    placeholder: '请输入角色编码',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "角色名", 
    type: 'input',
    name: "name", 
    value: '',
    maxlength: 20,
    placeholder: '请输入角色名',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "版本号", 
    type: 'input',
    name: "versionNo", 
    value: '',
    hidden: true,
    maxlength: 20,
    placeholder: '请输入版本号',
    reset() {
                this.value = "";
            },
  },
  { label: "备注", 
    type: 'textarea',
    name: "remark", 
    value: '',
    maxlength: 20,
    placeholder: '请输入备注',
    reset() {
                this.value = "";
            },
  },
 

]);
const tableFooter = ref<TableFooter>();
const menuDialogRef = ref<DialogType>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propValue = item[it.name];
    it.value = propValue;
  });
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(updateRole,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
   let params = {
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryRoleList,params);
}

function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
  // alert("params"+JSON.stringify(params));
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveRole,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
  if (data.length > 0) {
    showConfirmBox("是否要删除此数据项，删除后不恢复？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let params: number[] = [];
        data.forEach((item: { roleOid: any }) => {
          params.push(item.roleOid);
        });
        post({
          url: deleteBatchRole,
          data: {
            keyOids: params,
          },
        })
          .then(() => {
            doRefresh();
            showSuccessMessage("删除成功");
          })
          .catch(console.log);
      })
      .catch(() => {
        showInfoMessage("取消删除");
      });
  } else {
    showErrorMessage("请选择要删除的数据项");
  }
}

function searchForm(data: any) {
    let params = {
    searchConditionVOList: data,
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryRoleList,params);
}

function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}

function showMenu(item: RoleModel) {
  menuData.length = 0;
  defaultCheckedKeys.length = 0;
  defaultExpandedKeys.length = 0;
  selectedKeys.length = 0;
  currentRoleOid = item.roleOid;
  post({
    url: getMenuListByRoleId,
    data: {
      id: item.roleOid,
    },
  })
    .then((res: any) => {
      let menuList : any = [];
      menuList = allMenuToTree(res.data);
      menuData.push(...menuList);
      handleRoleMenusSelected(menuData);
      menuDialogRef.value?.show(() => {
        var params = {
          roleOid : currentRoleOid,
          keyOids : selectedKeys,
        }
        submitForm(saveUserRight,params)
        menuDialogRef.value?.close();
        //初始化
        selectedKeys.length = 0;
      });
    })
    .catch(console.log);
}

function handleRoleMenusSelected(menus: Array<any>) {
  // console.log("menus"+JSON.stringify(menus));
  menus.forEach((it: any) => {
    var isLeaf = it.children.length === 0 ? true : false;
    if(currentRoleOid ===  it.roleOid){
        if(!defaultCheckedKeys.includes(it.menuOid) && it.parentOid !== 0 && isLeaf){
          defaultCheckedKeys.push(it.menuOid);
        }
        //处理根节点
        if(!selectedKeys.includes(it.menuOid)){
          selectedKeys.push(it.menuOid); 
        }
    }
    if (it.children) {
      defaultExpandedKeys.push(it.menuOid);
      handleRoleMenusSelected(it.children);
    }
  });
}

function handleCheckChange(data: any, checked: any, indeterminate: any){
  if(checked || indeterminate){
    if(!selectedKeys.includes(data.menuOid)){
      selectedKeys.push(data.menuOid);
    }
  }else{
    selectedKeys.splice(selectedKeys.indexOf(data.menuOid),1);
  }
}
onMounted(doRefresh);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
